// 获取行者列表云函数
"use strict";

const db = uniCloud.database();
const usersCollection = db.collection("users");

exports.main = async (event, context) => {
  try {
    // 获取查询参数
    const {
      page = 1,
      pageSize = 10,
      keyword = "",
      gender = "",
      status = "",
    } = event;

    // 构建查询条件
    const condition = {
      user_type: "walker", // 专门查询行者用户
    };

    // 关键词搜索（支持userId、nickname、phone三个字段）
    if (keyword) {
      condition.$or = [
        { userId: new RegExp(keyword, "i") },
        { nickname: new RegExp(keyword, "i") },
        { phone: new RegExp(keyword, "i") },
      ];
    }

    // 按性别筛选
    if (gender !== "") {
      condition.gender = parseInt(gender);
    }

    // 按状态筛选
    if (status !== "") {
      condition.status = parseInt(status);
    }

    // 查询总数
    const countResult = await usersCollection.where(condition).count();
    const total = countResult.total;

    // 查询分页数据
    const result = await usersCollection
      .where(condition)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy("register_date", "desc")
      .get();

    return {
      code: 0,
      message: "获取行者列表成功",
      data: {
        list: result.data,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    };
  } catch (error) {
    console.error("获取行者列表失败:", error);
    return {
      code: -1,
      message: "获取行者列表失败: " + error.message,
    };
  }
};
